//
//  BEURLExtension.swift
//  BasicExtensions
//
//  Created by Fanxx on 2018/3/23.
//  Copyright © 2018年 fanxx. All rights reserved.
//


import UIKit

extension URL {
    /// 格式化查询参数
    public var queryItems: [URLQueryItem]? {
        return URLComponents(url: self, resolvingAgainstBaseURL: false)?.queryItems
    }
    /// 格式化查询参数
    @available(iOS 11.0, *)
    public var percentEncodedQueryItems: [URLQueryItem]? {
        return URLComponents(url: self, resolvingAgainstBaseURL: false)?.percentEncodedQueryItems
    }
    /// 添加查询参数
    public func byAppendingQuery(_ name:String, value: String) -> URL {
        if var cp = URLComponents(url: self, resolvingAgainstBaseURL: false) {
            let item = URLQueryItem(name: name, value: value)
            if var items = cp.queryItems {
                if var fisrt = items.first(where: { $0.name == name }) {
                    fisrt.value = value
                }else{
                    items.append(item)
                }
            }else{
                cp.queryItems = [item]
            }
            return cp.url!
        }else{
            return self
        }
    }
    /// 添加查询参数
    public func byAppendingQuery(_ params: [String: String]) -> URL {
        if var cp = URLComponents(url: self, resolvingAgainstBaseURL: false) {
            var items = cp.queryItems ?? []
            params.forEach { item in
                if var first = items.first(where: { $0.name == item.key }) {
                    first.value = item.value
                }else{
                    items.append(.init(name: item.key, value: item.value))
                }
            }
            cp.queryItems = items
            return cp.url!
        }else{
            return self
        }
    }
    /// 删除查询参数
    public func byRemovingQuery() -> URL {
        if self.query != nil, var cp = URLComponents(url: self, resolvingAgainstBaseURL: false) {
            cp.query = nil
            return cp.url!
        }else{
            return self
        }
    }
    ///通过外部浏览器打开
    public func open() {
        if #available(iOS 10.0, *) {
            //系统版本高于10.0
            UIApplication.shared.open(self, options: [:], completionHandler: nil)
        } else {
            //系统版本低于10.0
            DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.001) {
                UIApplication.shared.openURL(self)
            }
        }
    }
    /// 获取系统文件目录
    public static func fileDirectory(for directory:FileManager.SearchPathDirectory = .documentDirectory, in domain: FileManager.SearchPathDomainMask = .userDomainMask) -> URL {
        return FileManager.default.urls(for: directory, in: domain)[0]
    }
}

